import postcss from 'postcss'
import {AutoAdaptiveConfig} from './AutoAdaptiveConfig'
import JsonUtil from "./JsonUtil";

const defaultConfig: AutoAdaptiveConfig = {
    designWidth: 1920,
    minWidth: 1440,
    minPx: 1
}

const processed = Symbol('processed')

const postcssAutoAdaptive = (options = {}) => {
    const configs: AutoAdaptiveConfig = {...defaultConfig, ...options}

    return {
        postcssPlugin: 'postcss-auto-adaptive',
        Root(node, {Rule}) {
            for (const nodeItem of node.nodes) {
                console.log(nodeItem)
                console.log(nodeItem.raws)
            }
        },
        Declaration(node, {Rule}) {
            if (!node[processed]) {
                let newRule = new Rule({selector: 'a', source: node.source})
                newRule[processed] = true
                node.root().append(newRule)
            }
             let newRule = new Rule({ selector: 'a', source: node.source })
             newRule.append(node)
             if (!Rule[processed]) {
               process(rule)
               rule[Rule] = true
             }
            //

            if (decl.value.includes('px')) {
              console.log(decl)
              console.log(decl.parent.nodes)
              const value = decl.value.split('px')[0]
              if (value > configs.minPx) {
                // 得到设计稿下的百分比，*100得到百分比
                const vwValue = parseFloat(((100 * value) / configs.designWidth).toFixed(3)) +'vw'
                // 得到最小尺寸下的px *最小尺寸除以设计尺寸
                const minPxValue = parseFloat(((value * configs.minWidth) / configs.designWidth).toFixed(3)) + 'px'
                console.log(minPxValue)
                decl.value = vwValue
              }
            }
        }
    }
}
postcssAutoAdaptive.postcss = true

// @ts-ignore
postcss([postcssAutoAdaptive]).process(`@media (max-width: 767px) {
        .markdown-body {
            padding: 15px;
        }
    }`, {from: undefined}).then(res => {
    // console.log(res)
})
